import express from 'express'
import db from '../config/db.js'

const router = express.Router()

// GET /api/trainings  可选 ?level=零基础|初学者|进阶
router.get('/', async (req, res) => {
  const { level } = req.query
  let sql = 'SELECT id, title, category, price, level, duration, durationRange, equipment, cover FROM trainings'
  const params = []
  if (level) {
    sql += ' WHERE level = ?'
    params.push(level)
  }
  try {
    const conn = await db.getConnection()
    conn.query(sql, params, (err, results) => {
      conn.release()
      if (err) return res.status(500).json({ message: '数据库查询失败', error: String(err) })
      res.json(results)
    })
  } catch (e) {
    res.status(500).json({ message: '数据库连接失败', error: String(e) })
  }
})

// GET /api/trainings/:id
router.get('/:id', async (req, res) => {
  const { id } = req.params
  try {
    const conn = await db.getConnection()
    conn.query(
      'SELECT id, title, category, price, level, duration, durationRange, equipment, cover FROM trainings WHERE id = ? LIMIT 1',
      [id],
      (err, results) => {
        conn.release()
        if (err) return res.status(500).json({ message: '数据库查询失败', error: String(err) })
        if (!results || results.length === 0) return res.status(404).json({ message: '未找到该训练' })
        res.json(results[0])
      }
    )
  } catch (e) {
    res.status(500).json({ message: '数据库连接失败', error: String(e) })
  }
})

export default router

